package sys

import (
	"database/sql/driver"
	"encoding/json"
	"errors"
	"github.com/vueadmin/utils/conv"
	"strings"
)

type Validate []interface{}

func (validate Validate) Value() (driver.Value, error) {
	if len(validate) > 0 {
		return conv.SliceToString(validate), nil
	} else {
		return "", nil
	}
}

func (validate *Validate) Scan(value interface{}) error {
	str, ok := value.([]byte)
	if !ok {
		return errors.New("不匹配的数据类型")
	}
	var slice []interface{}
	for _, v := range strings.Split(string(str), ",") {
		slice = append(slice, v)
	}
	*validate = slice
	return nil
}

type ItemConfig []map[string]interface{}

func (itemConfig ItemConfig) Value() (driver.Value, error) {
	str, err := json.Marshal(itemConfig)
	if err != nil {
		return nil, err
	}
	return string(str), nil
}

func (itemConfig *ItemConfig) Scan(value interface{}) error {
	str, ok := value.([]byte)
	if !ok {
		return errors.New("不匹配的数据类型")
	}
	json.Unmarshal(str, &itemConfig)
	return nil
}

type OtherConfig map[string]interface{}

func (otherConfig OtherConfig) Value() (driver.Value, error) {
	str, err := json.Marshal(otherConfig)
	if err != nil {
		return nil, err
	}
	return string(str), nil
}

func (otherConfig *OtherConfig) Scan(value interface{}) error {
	str, ok := value.([]byte)
	if !ok {
		return errors.New("不匹配的数据类型")
	}
	json.Unmarshal(str, &otherConfig)
	return nil
}

type Field struct {
	Id               uint        `gorm:"primaryKey" form:"id" json:"id"`
	MenuId           string      `form:"menu_id" json:"menu_id"`
	Title            string      `form:"title" json:"title"`
	Field            string      `form:"field" json:"field"`
	Type             int8        `form:"type" json:"type"`
	ListShow         int8        `form:"list_show" json:"list_show"`
	SearchType       int8        `form:"search_type" json:"search_type"`
	PostStatus       bool        `form:"post_status" json:"post_status"`
	CreateTableField int8        `form:"create_table_field" json:"create_table_field"`
	Validate         string      `form:"validate" json:"validate"`
	Rule             *string     `form:"rule" json:"rule"`
	Sortid           int32       `form:"sortid" json:"sortid"`
	Sql              string      `form:"sql" json:"sql"`
	DefaultValue     string      `form:"default_value" json:"default_value"`
	Datatype         string      `form:"datatype" json:"datatype"`
	Length           string      `form:"length" json:"length"`
	ShowCondition    string      `form:"show_condition" json:"show_condition"`
	BelongTable      string      `form:"belong_table" json:"belong_table"`
	OtherConfig      OtherConfig `form:"other_config" json:"other_config"`
	Width            string      `form:"width" json:"width"`
	ItemConfig       ItemConfig  `form:"item_config" json:"item_config"`
	DatetimeConfig   string      `form:"datetime_config" json:"datetime_config"`
	Indexdata        string      `form:"indexdata" json:"indexdata"`
}

func (Field) TableName() string {
	return "cd_field"
}
